package tushare

import (
	"tushare/model/mysql"
)

type Angle struct {
	Id        int64   `json:"id"`
	TsCode    string  `json:"ts_code"`
	Name      string  `json:"name"`
	TradeDate string  `json:"trade_date"`
	AvgAmount float64 `json:"avg_amount"`
	AvgType   int64   `json:"avg_type"`
	Close     float64 `json:"close"`
	Angle     float64 `json:"angle"`
}

func AngleCreate(a Angle) {
	mysql.DB.Table("tushare_angle").Create(&a)
}

func AngleList(page, pageSize int64, tradeDate string, avg_type int64) []Angle {
	page = page
	pageSize = pageSize
	offset := (page - 1) * pageSize

	bf := []Angle{}
	mysql.DB.Table("tushare_angle").Where("trade_date = ? and avg_type = ?", tradeDate, avg_type).Order("angle DESC").Limit(pageSize).Offset(offset).Scan(&bf)
	return bf
}

func AngleCount(tradeDate string, avg_type int64) int64 {
	var count int64
	mysql.DB.Table("tushare_angle").Where("trade_date = ? and avg_type = ?", tradeDate, avg_type).Count(&count)
	return count
}

//角度次日涨跌情况
type angleNextDayRiseStruct struct {
	TsCode    string  `json:"ts_code"`
	Name      string  `json:"name"`
	TradeDate string  `json:"trade_date"`
	Angle     float64 `json:"angle"`
	ImAmount  float64 `json:"im_amount"`
}

func AngleNextDayRise(page, pageSize, avgType int64, tradeDate string) []angleNextDayRiseStruct {

	page = page
	pageSize = pageSize
	offset := (page - 1) * pageSize

	andrs := []angleNextDayRiseStruct{}

	mysql.DB.Table(`tushare_angle`).Select(` 
	tushare_angle.ts_code as ts_code,
		tushare_angle.name as name,
		tushare_angle.trade_date as trade_date,
		tushare_angle.angle as angle,
		tushare_stock.im_amount as im_amount
	`).Joins(`
	LEFT JOIN tushare_stock ON tushare_angle.ts_code = tushare_stock.ts_code
	`).Where(`
	tushare_angle.trade_date = ?
AND tushare_angle.avg_type = ?
AND tushare_angle.angle >= 50
AND tushare_stock.im_amount > 0
	`, tradeDate, avgType).Order(`
	tushare_stock.im_amount DESC
	`).Limit(pageSize).Offset(offset).Scan(&andrs)
	return andrs
}

func AngleNextDayRiseCount(avgType int64, tradeDate string) int64 {
	var count int64

	mysql.DB.Table(`tushare_angle`).Select(` 
	tushare_angle.id as id,
	`).Joins(`
	LEFT JOIN tushare_stock ON tushare_angle.ts_code = tushare_stock.ts_code
	`).Where(`
	tushare_angle.trade_date = ?
AND tushare_angle.avg_type = ?
AND tushare_angle.angle >= 50
AND tushare_stock.im_amount > 0
	`, tradeDate, avgType).Count(&count)
	return count
}

func AngleAvgLineCount(avgType, angle int64, tradeDate string) int64 {
	var count int64

	mysql.DB.Table(`tushare_angle`).Select(` 
	id
	`).Where(`
	trade_date = ?
AND avg_type = ?
AND angle >= ?
	`, tradeDate, avgType, angle).Count(&count)
	return count
}
